package com.slipper.codeless.resolve.delete;

import com.slipper.constants.Constants;
import com.slipper.exception.CommonException;
import com.slipper.system.codeless.bo.DataFieldBO;
import com.slipper.system.codeless.bo.DataModelBO;
import com.slipper.util.Tool;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class DeleteResolver {
    public Delete resolve(DataModelBO dataModel, Map<String, Object> data) {
        if (dataModel == null) throw new CommonException("数据模型不存在！");
        if (data == null || data.isEmpty()) throw new CommonException("未提交要更新的数据！");

        @SuppressWarnings("unchecked")
        List<Map<String, Object>> dataList = (List<Map<String, Object>>) data.get("dataList");

        Delete delete = new Delete();
        delete.setTableName(dataModel.getCode());

        DataFieldBO primaryKeyField = dataModel.getFieldList().stream()
                .filter(dataField -> Constants.YES.equals(dataField.getPrimaryKey()))
                .findFirst()
                .orElse(null);
        if (primaryKeyField == null) throw new CommonException("数据模型未配置主键字段！");
        delete.setPkIdName(primaryKeyField.getFieldName());

        String pkId = (String) data.get(primaryKeyField.getFieldName());
        if (Tool.isNotBlank(pkId)) {
            delete.addPkId(pkId);
        }

        if (dataList != null && !dataList.isEmpty()) {
            dataList.stream()
                    .map(item -> (String) item.get(primaryKeyField.getFieldName()))
                    .filter(Tool::isNotBlank)
                    .forEach(delete::addPkId);
        }
        return delete;
    }
}
